<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="数据状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:group:data:create']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:group:data:update']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:group:data:delete']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['system:group:data:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleClose"
          v-if="isShowClose"
        >关闭
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id" width="80"/>
      <el-table-column v-for="(column,index) in columns" :key="index" :label="column.label" align="center"
                       :prop="column.field" v-if="column.visible"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <template v-if="column.is_system == 1">{{ scope.row[column.field] }}</template>
          <template v-else>
            <template v-if="column.formType == 'select' || column.formType == 'radio' || column.formType == 'checkbox'">
              <template v-for="(arr) in column.keyRuleArr">
                <template v-if="arr.value == scope.row.groupValues[column.field]">{{ arr.label }}</template>
              </template>
            </template>
            <template v-else>
              {{ scope.row.groupValues[column.field] }}
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:group:data:update']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:group:data:delete']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="组合数据">
          <el-input v-model="groupInfo.name" :disabled="true"/>
        </el-form-item>

        <!--动态字段-->
        <div v-for="(dyField,index) in groupInfo.fields">
          <dynamic-form :key-label="dyField.name" :key-value.sync="form.groupValues[dyField.field]"
                        :key-field="`groupValues.${dyField.field}`"
                        :key-type="dyField.type" :key-rule="dyField.keyRule" :key-rule-arr="dyField.keyRuleArr"/>
        </div>
        <!--动态字段-->

        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  groupDataLists,
  groupDataCreate,
  groupDataDelete,
  groupDataView,
  groupDataUpdate
} from "@/api/system/group-data";
import {groupView} from "@/api/system/group";
import {deepClone} from "@/utils";
import DynamicForm from "@/views/components/dynamicForm/index.vue";

export default {
  name: "Data",
  dicts: ['sys_normal_disable'],
  components: {
    DynamicForm
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dataList: [],
      // 默认字典类型
      defaultDictType: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: undefined,
        status: undefined
      },
      groupInfo: {},
      // 表单参数
      form: {},
      // 增加动态字段后的原始表单字段
      origenForm: {
        id: undefined,
        groupId: undefined,
        groupValues: {},
        sort: 0,
        status: "0",
        remark: undefined
      },
      // 列信息
      columns: [
        {key: 9999910, is_system: 1, label: `排序`, field: 'sort', visible: true, formType: '', keyRuleArr: []},
        {key: 9999911, is_system: 1, label: `备注`, field: 'remark', visible: true, formType: '', keyRuleArr: []},
        {
          key: 9999912,
          is_system: 1,
          label: `创建时间`,
          field: 'createdAt',
          visible: true,
          formType: '',
          keyRuleArr: []
        },
      ],
      // 表单校验
      rules: {
        // label: [
        //   {required: true, message: "数据标签不能为空", trigger: "blur"}
        // ],
        // value: [
        //   {required: true, message: "数据键值不能为空", trigger: "blur"}
        // ],
        sort: [
          {required: true, message: "数据顺序不能为空", trigger: "blur"}
        ]
      },
      isShowClose: true
    };
  },
  created() {
    let id = undefined
    if (this.$route.params.id) {
      id = this.$route.params.id
      // 直接
    } else {
      // 外部
      id = this.$route.query.id;
      this.isShowClose = false
    }
    if (id != "" && id != undefined) {
      this.queryParams.groupId = this.origenForm.groupId = id
      this.getGroup(id);
    } else {
      this.$modal.msgError("组合数据ID错误");
    }
  },
  methods: {
    /** 查询字典类型详细 */
    getGroup(id) {
      groupView(id).then(response => {
        this.groupInfo = response.data
        let i = 0
        response.data.fields.forEach((item, index) => {
          // 动态表单字段
          this.origenForm.groupValues[item.field] = ""
          // 动态表单验证
          if (item.is_require == '1') {
            this.rules[`groupValues.${item.field}`] = [{
              required: true,
              message: `请填写或选择${item.name}内容!`,
              trigger: "blur"
            }]

            // 动态插入列表表头
            this.columns.splice(i, 0, {
              key: index,
              is_system: 0,
              label: item.name,
              field: item.field,
              visible: true,
              formType: item.type,
              keyRuleArr: item.keyRuleArr
            })
            i++
          }
        })
        this.reset()
        // 处理创建或修改表单数据
        this.getList();
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      groupDataLists(this.queryParams).then(response => {
        this.dataList = response.data.list;
        this.total = response.data.count;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {}
      this.form = deepClone(this.origenForm);
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 返回按钮操作 */
    handleClose() {
      const obj = {path: "/system/group"};
      this.$tab.closeOpenPage(obj);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加组合数据";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      groupDataView(id).then(response => {
        this.form = Object.assign(this.form, response.data);
        this.open = true;
        this.title = "修改组合数据";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            groupDataUpdate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            groupDataCreate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除为"' + ids + '"的数据项？').then(function () {
        return groupDataDelete(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/dict/data/export', {
        ...this.queryParams
      }, `data_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
